# coding=utf-8
import baseFunctions as bf
import cv2
import time
import numpy as np
import os
from PIL import ImageGrab as ig
# {"trigger": "03", "btn": "03" , "descript":"打开游戏" ,"clicked": False },
# {"trigger": "yinsi", "btn": "agree" , "descript":"隐私协议" ,"clicked": False },
# {"trigger": "login", "btn": "entergame" , "descript":"登录" ,"clicked": False },
# {"trigger": "loginfail", "btn": "continue" , "descript":"登录失败" ,"clicked": False },
# {"trigger": "gonggao", "btn": "gonggaoguanbi" , "descript":"公告" ,"clicked": False },
# {"trigger": "login2", "btn": "login2btn" , "descript":"登录2" ,"clicked": False },
# {"trigger": "timeout", "btn": "gonggaoguanbi" , "descript":"超时" ,"clicked": False },
# {"trigger": "selectrole", "btn": "entergame2" , "descript":"选择角色完成" ,"clicked": False },
# {"trigger": "kezhuanzhi", "btn": "entergame2" , "descript":"kezhuanzhi_btn" ,"clicked": False },
imData = []
imMap = {}
lastModifyTimeMap = {}
def getImData(csvName):
    global imData
    file_path = f"{os.path.dirname(__file__)}/lzgsj/csv/{csvName}.csv"
    if file_path not in lastModifyTimeMap or os.path.getmtime(file_path) > lastModifyTimeMap[file_path]:
        with open(file_path, 'r', encoding='utf-8') as f:
            for idx,line in enumerate(f.readlines()):
                if idx == 0:
                    continue
                line = line.strip()
                datas = line.split(',')
                
                if line == '' or len(datas) < 4:
                    continue
                imData.append({
                    "trigger":datas[0],
                    "btn": datas[1] ,
                    "descript":datas[2] ,
                    "clickNum": int(datas[3]),
                    "state":datas[4],
                    "tostate":datas.__len__() >= 6 and datas[5] or '',
                })
        lastModifyTimeMap[file_path] = os.path.getmtime(file_path)
    return imData
def getImread(path):
    file_path = f"{os.path.dirname(__file__)}/lzgsj/images/{path}"
    if not os.path.exists(file_path):
        print(f"file_path {file_path} not exists")
        return None
    if not path in imMap:
        imMap[path] = cv2.imread(file_path, cv2.IMREAD_GRAYSCALE)
    return imMap[path]

def openBh3Auto2():
    cur_state = "登录"
    while True:
        imData = getImData('lzgsj')
        # print('imData',imData.__len__())
        excludes = []
        for item in imData:
            if item['clickNum'] == 0 or cur_state != item['state']:
                # excludes.append(item)
                # imData.remove(item)
                continue
            if item['clickNum'] != -1:
                item['clickNum'] -= 1
            img_view = getImread(item["trigger"] + ".png")
            img_click = getImread(item["btn"] + ".png")
            if img_view is None or img_click is None:
                continue
            excludes.append(item['trigger'])
            if bf.existElement(img_view):
                pos = bf.findLocWithKp(img_click)
                if pos[0] >= 1 and pos[1] >= 1:
                    bf.animateMoveAndClick(bf.getCurPos(), pos, durTime=0)
                    print("点击：", item["descript"])
                    cur_state = item["state"]
                    print("当前状态：", cur_state)


if __name__ == '__main__':
    # openBh3Auto2()
    while True:
        rect = bf.getApplicationWindowRect('雷电模拟器')
        renwuColor = bf.getPixelColor(rect['left']+ 246/1164*rect['width'],rect['top']+ 190/688*rect['height'])
        print(renwuColor)
        if renwuColor[0] == 181 and renwuColor[1] == 181 and renwuColor[2] == 181:
            print('找到箭头')
    # 1002 597
    # 212 169
    # collectCoinsAuto()
    # adventureAuto()
